package com.bwt.sparseArray;

public class SparseArray {

	public static void main(String[] args) {
		//创建一个原始的二位数组 11* 11
		int chessArr1[][] = new int[11][11];
		chessArr1[1][2] = 1;
		chessArr1[2][3] = 2;
		chessArr1[5][5] = 2;

		System.out.println("输出原始的二维数组");
		for (int[] row : chessArr1) {
			for (int data : row) {
				System.out.printf("%s\t", data);
			}
			System.out.println();
		}

		//将二维数组转为稀疏数组
		//1. 先遍历二维数组 得到非零的数组数组
		int sum = 0;
		for (int[] row : chessArr1) {
			for (int data : row) {
				if (data != 0) {
					sum++;
				}
			}
		}

		//创建稀疏数组
		int sparseArr[][] = new int[sum + 1][3];
		//给稀疏数组赋值
		sparseArr[0][0] = 11;
		sparseArr[0][1] = 11;
		sparseArr[0][2] = sum;

		//遍历二维数组, 将非0的值赋值给稀疏数组
		int pointer = 1;
		for (int i = 0; i < chessArr1.length; i++) {
			for (int j = 0; j < chessArr1[i].length; j++) {
				if (chessArr1[i][j] != 0) {
					sparseArr[pointer][0] = i;
					sparseArr[pointer][1] = j;
					sparseArr[pointer][2] = chessArr1[i][j];
					pointer++;
				}
			}
		}
		System.out.println("转换后的稀疏数组");
		for (int[] row : sparseArr) {
			for (int data : row) {
				System.out.printf("%s\t", data);
			}
			System.out.println();
		}

		//将稀疏数组恢复成原始的二维数组
		int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
		for (int i = 1; i <= sparseArr[0][2]; i++) {
			chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
		}

		System.out.println("恢复后的稀疏数组");
		for (int[] row : chessArr2) {
			for (int data : row) {
				System.out.printf("%s\t", data);
			}
			System.out.println();
		}
	}
}
